<?php
// +----------------------------------------------------------------------
// | [KyPHP System] Copyright (c) 2020 http://www.kuryun.com/
// +----------------------------------------------------------------------
// | [KyPHP] 并不是自由软件,你可免费使用,未经许可不能去掉KyPHP相关版权
// +----------------------------------------------------------------------
// | Author: fudaoji <fdj@kuryun.cn>
// +----------------------------------------------------------------------
/**
 * Created by PhpStorm.
 * Script Name: Minitemplate.php
 * Create: 2020/7/24 16:17
 * Description: 小程序模板库管理
 * Author: fudaoji<fdj@kuryun.cn>
 */
namespace app\admin\controller;
use app\common\model\MiniTemplate as Mt;
use ky\MiniPlatform\Request\WxaAddToTemplate;
use ky\MiniPlatform\Request\WxaDeleteTemplate;
use ky\MiniPlatform\Request\WxaGetTemplateDraftList;
use ky\MiniPlatform\Request\WxaGetTemplateList;
use ky\MiniPlatform\RequestClient;
use think\facade\Log;

class Minitemplate extends Base
{
    /**
     * @var \app\common\model\MiniTemplate
     */
    private $model;
    /**
     * @var RequestClient
     */
    private $client;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = model('miniTemplate');
        $this->client = new RequestClient();
    }

    /**
     * 小程序模板库
     * @return mixed
     * Author: fudaoji<fdj@kuryun.cn>
     * @throws \think\exception\DbException
     */
    public function index(){
        $type = input('type', Mt::TEMPLATE);
        $where = ['type' => $type];
        $data_list = $this->model->page($this->pageSize, $where, ['upload_time' => 'desc'], true, true);
        $this->assign['page'] = $data_list->appends(['type' => $type])->render();
        $this->assign['data_list'] = $data_list;
        $this->assign['type'] = $type;
        return $this->show();
    }

    /**
     * 删除草稿
     * @throws \Exception
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function delTemplatePost(){
        if(request()->isPost()) {
            $token = controller('mini/mini', 'event')->getOpenPlatform()->access_token->getToken()['component_access_token'];
            $request = new WxaDeleteTemplate();
            $template_id = input('post.id', '');
            $request->setTemplateId($template_id);
            $response = $this->client->execute($request, $token);
            if ($response['errcode'] == 0) {
                $this->model->delByMap(['type' => Mt::TEMPLATE, 'template_id' => $template_id]);
                $this->success('操作成功');
            } else {
                $this->error($response['errmsg']);
            }
        }
    }

    /**
     * 添加草稿到模板库
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function addToTemplatePost(){
        if(request()->isPost()) {
            $token = controller('mini/mini', 'event')->getOpenPlatform()->access_token->getToken()['component_access_token'];
            $request = new WxaAddToTemplate();
            $request->setDraftId(input('post.draft_id', ''));
            $response = $this->client->execute($request, $token);
            if ($response['errcode'] == 0) {
                $this->success('操作成功');
            } else {
                $this->error($response['errmsg']);
            }
        }
    }

    /**
     * 同步模板库
     * @author fudaoji<fdj@kuryun.cn>
     */
    public function syncPost(){
        if(request()->isPost()){
            $token = controller('mini/mini', 'event')->getOpenPlatform()->access_token->getToken()['component_access_token'];
            $request = new WxaGetTemplateList();
            $response = $this->client->setCheckRequest(false)->execute($request, $token);

            if(isset($response['errcode']) && $response['errcode'] === 0) {
                $list = $response['template_list'];
                $insert_data = [];
                $ids = [];
                $db_ids = $this->model->getField('template_id', ['type' => Mt::TEMPLATE], true);

                //微信服务器数据与库中数据比较，新数据入库
                foreach ($list as $vo) {
                    if(! in_array($vo['template_id'], $db_ids)) {
                        $temp = [
                            'template_id'      => $vo['template_id'],
                            'user_desc'     => $vo['user_desc'],
                            'user_version'  => $vo['user_version'],
                            'upload_time'   => $vo['create_time'],
                            'type'          => Mt::TEMPLATE,
                            'source_miniprogram_appid' => $vo['source_miniprogram_appid'],
                            'source_miniprogram' => $vo['source_miniprogram'],
                            'developer' => $vo['developer']
                        ];
                        array_push($insert_data, $temp);
                    }
                    $ids[] = $vo['template_id'];
                }

                !empty($insert_data) && $this->model->addBatch($insert_data);

                //库中数据与微信服务器数据比较，不存在的删除
                $del_id = array_diff($db_ids, $ids);
                count($del_id) && $this->model->delByMap(['template_id' => ['in', $del_id], 'type' => Mt::TEMPLATE]);
            }
            $result = true;

            if($result){
                $this->success('操作成功');
            }else{
                $this->error('系统出错，请联系管理员');
            }
        }
    }

    /**
     * 同步草稿数据
     * @author fudaoji<fdj@kuryun.cn>
     */
    public function syncDraftPost(){
        if(request()->isPost()){
            try {
                $token = controller('mini/mini', 'event')->getOpenPlatform()->access_token->getToken()['component_access_token'];
                $request = new WxaGetTemplateDraftList();
                $response = $this->client->setCheckRequest(false)->execute($request, $token);

                if(isset($response['errcode']) && $response['errcode'] === 0) {
                    $list = $response['draft_list'];
                    $insert_data = [];
                    $draft_ids = [];
                    $db_ids = $this->model->getField('template_id', ['type' => Mt::DRAFT], true);

                    //微信服务器数据与库中数据比较，新数据入库
                    foreach ($list as $vo) {
                        if(! in_array($vo['draft_id'], $db_ids)) {
                            $temp = [
                                'template_id'      => $vo['draft_id'],
                                'user_desc'     => $vo['user_desc'],
                                'user_version'  => $vo['user_version'],
                                'upload_time'   => $vo['create_time'],
                                'type'          => Mt::DRAFT,
                                'source_miniprogram_appid' => $vo['source_miniprogram_appid'],
                                'source_miniprogram' => $vo['source_miniprogram'],
                                'developer' => $vo['developer']
                            ];
                            array_push($insert_data, $temp);
                        }
                        $draft_ids[] = $vo['draft_id'];
                    }

                    !empty($insert_data) && $this->model->addBatch($insert_data);

                    //库中数据与微信服务器数据比较，不存在的删除
                    $del_id = array_diff($db_ids, $draft_ids);
                    count($del_id) && $this->model->delByMap(['template_id' => ['in', $del_id], 'type' => Mt::DRAFT]);
                }
                $result = true;
            }catch (\Exception $e){
                Log::write($e->getMessage());
                $result = false;
            }

            if($result){
                $this->success('操作成功');
            }else{
                $this->error('系统出错，请联系管理员');
            }
        }
    }
}